/**
 * JAVACC DEMO 1.0
 */
package com.apache.uct.controller;

import com.apache.api.manager.BaseManager;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.api.vo.Token;
import com.apache.database.constant.SystemTools;
import com.apache.database.constant.Validator;
import com.apache.database.model.Page;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.BaseAction;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.entity.Dept;
import com.apache.uct.common.entity.Org;
import com.apache.uct.common.entity.User;
import com.apache.uct.manager.DeptManager;
import com.apache.uct.manager.OrgManager;
import com.apache.uct.manager.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  用户管理Action
 *
 * @author iussoft 创建时间：2016-3-10
 */
@Controller
@RequestMapping("uct/user/")
public class UserAction extends BaseAction<User> {

    @Autowired
    private UserManager userManager;

    @Autowired
    private ProxyManager uctProxyManager;

    @Autowired
    private OrgManager orgManager;

    @Autowired
    private DeptManager deptManager;

    /**
     * 功能说明：跳转到列表查询页面
     */
    @RequestMapping("list.action")
    public ModelAndView list(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(LIST);
        view.addObject("pluginsSwitch", SystemTools.getInstance().getValue("org_act_switch"));
        return view;
    }

    //进入回收站
    @RequestMapping("gc_list.action")
    public ModelAndView gcList(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(getPrefix() + "hs");
        view.addObject("pluginsSwitch", SystemTools.getInstance().getValue("org_act_switch"));
        return view;
    }

    @RequestMapping("user!data.action")
    @ResponseBody
    protected Object data(HttpServletRequest request, String page, String rows) {
        ParamsVo<User> vo = new ParamsVo<User>();
        User user = new User();
        if (Validator.isNotNull(request.getParameter("orgId"))) {
            user.setOrgId(request.getParameter("orgId"));
        } else {
            LoginUser loginUser = PBOSSOTools.getLoginUser(request);
            if ("1".equals(SystemTools.getInstance().getValue("org_act_switch")) && "0"
                    .equals(loginUser.getSysFlag())) {//是否开启管理子机构
                ParamsVo<Org> vo2 = new ParamsVo<Org>();
                Org org = new Org();
                org.setFatherId(loginUser.getOrgId());
                vo2.setObj(org);
                List<Org> orgs = orgManager.getList(vo2);
                if (!Validator.isEmpty(orgs)) {
                    int count = orgs.size();
                    StringBuffer sb = new StringBuffer("'" + loginUser.getOrgId() + "',");
                    for (int i = 0; i < count; i++) {
                        if (i == count - 1) {
                            sb.append("'" + orgs.get(i).getOrgId() + "'");
                        } else {
                            sb.append("'" + orgs.get(i).getOrgId() + "',");
                        }
                    }
                    vo.setParams("orgIds", sb.toString());
                } else {
                    vo.setParams("orgIds", "'" + loginUser.getOrgId() + "'");
                }
            }
        }
        if (Validator.isNotNull(request.getParameter("userEname"))) {
            user.setUserEname(request.getParameter("userEname"));
        }
        if (Validator.isNotNull(request.getParameter("userCname"))) {
            user.setUserCname(request.getParameter("userCname"));
        }
        if (Validator.isNotNull(request.getParameter("deptId"))) {
            user.setDeptId(request.getParameter("deptId"));
        }
        if (Validator.isNotNull(request.getParameter("userStatus"))) {
            user.setUserStatus(Integer.valueOf(request.getParameter("userStatus")));
        }
        vo.setParams("pageIndex", page);
        vo.setParams("pageSize", rows);
        vo.setObj(user);
        Page pageList = userManager.getPageInfo(vo);
        Map<String, Object> mapData = new HashMap<String, Object>();
        mapData.put("total", pageList.getCount());
        mapData.put("rows", pageList.getPageObjects());
        return mapData;
    }

    /**
     * 功能说明：跳转到新增页面
     */
    @Token(save = true)
    @RequestMapping("add.action")
    protected ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(ADD);
        User user = null;
        if (Validator.isNotNull(request.getParameter("id"))) {
            ParamsVo<User> vo = new ParamsVo<User>();
            vo.setInfoId(request.getParameter("id"));
            user = (User) userManager.getInfoById(vo);
        } else {
            user = new User();
        }
        view.addObject("item", user);
        view.addObject("pluginsSwitch", SystemTools.getInstance().getValue("org_act_switch"));
        return view;
    }

    @Token(remove = true)
    @RequestMapping(value = "/save.action", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg save(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute User item) {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        ParamsVo<User> vo = getParamsVo(request);
        long times = DateUtils.toLong(new Date());
        User user = this.getSessionUser(request);
        buildUserInfo(item, request, user.getOrgId());
        String md5Pass = request.getParameter("md5Pass");
        if (Validator.isNotNull(item.getUserId())) {//修改用户信息
            item.setUpdateTime(times);
            if (Validator.isNotNull(md5Pass)) {
                item.setUserPass(md5Pass.toLowerCase());
            }
            vo.setObj(item);
            boolean mark = userManager.editInfo(vo);
            if (!mark) {
                rmsg = getResultMsg(request, "用户信息修改失败！");
            }
        } else {//添加用户信息
            if (Validator.isNotNull(md5Pass)) {
                item.setUserPass(md5Pass.toLowerCase());
            }
            item.setCreateUser(user.getUserEname());
            item.setSysEname("uct");
            item.setUpdateCount(0);
            item.setCreateTime(times);
            vo.setObj(item);
            vo.setKey("checkUserEname");
            if (Validator.isNull(item.getDelStatus())) {
                item.setDelStatus("0");//默认机构用户
            } else {
                if (!"1".equals(getSysFlag(request))) {//不是系统用户无权建系统用户
                    item.setDelStatus("0");//默认机构用户
                }
            }
            if (Validator.isEmpty(item.getUserStatus())) {
                item.setUserStatus(1);//默认用户启用状态
            }
            vo.setObj(item);
            String msg = String.valueOf(userManager.execute(vo));
            if (Validator.isNotNull(msg)) {
                rmsg = getResultMsg(request, msg);
            } else {
                String id = userManager.saveInfo(vo);
                if (Validator.isNull(id)) {
                    rmsg = getResultMsg(request, "用户信息添加失败！");
                }
            }
        }
        return rmsg;
    }

    //删除用户信息（逻辑删除）
    @RequestMapping("userDel.action")
    @ResponseBody
    public ResultMsg deleteUser(HttpServletRequest request, String id) {
        ResultMsg rmsg = new ResultMsg("T", "删除成功！");
        ParamsVo<User> vo = getParamsVo(request);
        if (isNotNull(id)) {
            vo.setInfoId(id);
            vo.setParams("isDelete", "false");
            boolean mark = userManager.deleteInfo(vo);
            if (!mark) {
                rmsg = new ResultMsg("F", "删除失败！");
            }
        } else {
            rmsg.setFlag("H");
            rmsg.setMsg("请选择要删除的用户！");
        }
        return rmsg;
    }

    //删除用户信息（物理删除）
    @RequestMapping("del.action")
    @ResponseBody
    public ResultMsg delete(HttpServletRequest request, String id) {
        ResultMsg rmsg = new ResultMsg("T", "删除成功！");
        ParamsVo<User> vo = new ParamsVo<User>();
        if (isNotNull(id)) {
            vo.setInfoId(id);
            vo.setKey("deleteOrg");
            vo.setParams("infoType", "user");
            String msg = String.valueOf(uctProxyManager.doInvoke(vo));
            if (Validator.isNotNull(msg)) {
                rmsg.setFlag("F");
                rmsg.setMsg(msg);
            }
        } else {
            rmsg.setFlag("H");
            rmsg.setMsg("请选择要删除的用户！");
        }
        return rmsg;
    }

    //重新启用用户
    @RequestMapping("user!userReUserd.action")
    @ResponseBody
    public ResultMsg userReUserd(HttpServletRequest request, String id) {
        ResultMsg rmsg = new ResultMsg("T", "启用成功！");
        ParamsVo<User> vo = new ParamsVo<User>();
        if (isNotNull(id)) {
            vo.setInfoId(id);
            User user = (User) userManager.getInfoById(vo);
            user.setUserStatus(1);
            vo.setObj(user);
            boolean mark = userManager.editInfo(vo);
            if (!mark) {
                rmsg = new ResultMsg("F", "启用失败！");
            }
        } else {
            rmsg.setFlag("H");
            rmsg.setMsg("请选择要启用的用户！");
        }
        return rmsg;
    }

    @RequestMapping("update-pwd.action")
    public ModelAndView gotoUpdatePwd(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("uct/update-pwd");
        return view;
    }

    //修改密码
    @RequestMapping("user!update-pwd.action")
    @ResponseBody
    public ResultMsg updatePwd(HttpServletRequest request) {
        ResultMsg rmsg = new ResultMsg("T", "启用成功！");
        User user = this.getSessionUser(request);
        ParamsVo<User> vo = getParamsVo(request);
        vo.setInfoId(user.getUserId());
        user = (User) userManager.getInfoById(vo);
        String oldPass = request.getParameter("oldPass");

        if (false == oldPass.equals(user.getUserPass())) {
            return new ResultMsg("F", "旧密码错误，请重新输入！");
        }
        String newPass = request.getParameter("newPass");
        if (StrUtil.isNull(newPass)) {
            return new ResultMsg("F", "新密码不能为空！");
        }
        String newPass2 = request.getParameter("newPass2");
        if (false == newPass.equals(newPass2)) {
            return new ResultMsg("F", "新密码两次输入不一致！");
        }
        vo.setObj(user);
        user.setUserPass(newPass);
        boolean mark = userManager.editInfo(vo);
        if (!mark) {
            rmsg = new ResultMsg("F", "启用失败！");
        }
        return rmsg;
    }

    /**
     * description:  组织用户信息
     */
    private void buildUserInfo(User item, HttpServletRequest request, String orgId) {
        if (Validator.isNull(item.getUserId())) {
            if (Validator.isNull(item.getOrgId())) {
                item.setOrgId(orgId);
            }
        }
        ///进行修改操作(开启授权的机构用户不可以修改用户所在机构)
        if (Validator.isNotNull(item.getUserId()) && ("1".equals(getSysFlag(request)) || !"1"
                .equals(SystemTools.getInstance().getValue("org_act_switch")))) {
            if (Validator.isNull(item.getOrgId())) {
                item.setOrgId(request.getParameter("oldOrgId"));
            }
        }
        if (Validator.isNotNull(item.getOrgId())) {
            ParamsVo ovo = new ParamsVo();
            ovo.setInfoId(item.getOrgId());
            Org org = (Org) orgManager.getInfoById(ovo);
            item.setOrgEname(org.getOrgEname());
        }
        if (Validator.isNotNull(item.getUserId()) && Validator.isNull(item.getDeptId())) {
            item.setDeptId(request.getParameter("oldDeptId"));
        }
        if (Validator.isNotNull(item.getDeptId())) {
            ParamsVo ovo = new ParamsVo();
            ovo.setInfoId(item.getDeptId());
            Dept dept = (Dept) deptManager.getInfoById(ovo);
            item.setDeptName(dept.getDeptCname());
        }
    }

    protected BaseManager<User> getBaseManager() {
        return userManager;
    }

    protected String getPrefix() {
        return "uct/user-";
    }

    /**
     * 功能说明：通过主键获取实体
     */
    @RequestMapping("getById.action")
    @ResponseBody
    public Object getById(HttpServletRequest request, String id) {
        ParamsVo<User> vo = new ParamsVo<User>();
        User user = null;
        if (Validator.isNotNull(id)) {
            vo.setInfoId(id);
            user = (User) getBaseManager().getInfoById(vo);
        }
        return user;
    }
}
